package com.dingshi.security;

import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.RepairApi;
import com.dingshi.security.entity.Detail;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;

public class ServicesReceiverPaperActivity extends BaseActivity implements
		OnClickListener {
	protected static final int ID_LOADING = 2600;
	private static final int DATE_DIALOG_ID = 2700;
	private Button btn_back;
	private TextView title_text;
	private Button btn_right;
	private TextView edit_deparment;
	private TextView edit_device;
	private TextView edit_break;
	private EditText edit_confirm_break;
	private EditText edit_suggestion;
	private Spinner mSpinner;
	private TextView edit_predict_date;
	private EditText edit_repair_result;
	private String oddNum;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.services_track_paper);

		initTitle();
		initComponents();
		registerButton();
		oddNum = getIntent().getStringExtra("oddNum");
		getRepairDetail(oddNum, "1");
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, getResources().getString(
					R.string.login_loading));
			return dialog;
		case DATE_DIALOG_ID:
			int mYear = 0,
			mMonth = 0,
			mDay = 0;
			Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);

			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
	// the callback received when the user 'sets' the date in the dialog
		private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				edit_predict_date.setText(new StringBuilder().append(year + "-").append(
						monthOfYear + 1).append("-").append(dayOfMonth));

			}
		};
		private LinearLayout result_item;
		private LinearLayout predict_item;
		private Detail current;

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}

	private void getRepairDetail(String oddNum, String contentType) {
		RepairApi api = new RepairApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":{"dt":"2013-3-22 13:52:45","res":"","rdt":"","repd":null,
					//"d":"双兴监控室","p4":null,"e":"双兴球机1","p3":null,"p2":null,"p1":null,"ri":null,"xq":"双兴小区",
					//"rea":"","rd":"故障描述","eid":null,"i":"6","w":"维修人一","__type":"RepairBillDetailReturn:r",
					//"red":"诚旭网络监控维修","s":"张三","edt":"","stel":"13322332233","st":"2","rcd":"","rer":""},"t":0}


					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject obj = jsonEntity.getJSONObject("d");
							Detail detail = null;
							if (obj != null) {
								detail = new Detail();
								if (obj.has("i")) {
									detail.setI(obj.getString("i"));
								}
								if (obj.has("st")) {
									detail.setSt(obj.getString("st"));
								}
								if (obj.has("d")) {
									detail.setD(obj.getString("d"));
								}
								if (obj.has("xq")) {
									detail.setXq(obj.getString("xq"));
								}
								if (obj.has("s")) {
									detail.setS(obj.getString("s"));
								}
								if (obj.has("stel")) {
									detail.setStel(obj.getString("stel"));
								}
								if (obj.has("dt")) {
									detail.setDt(obj.getString("dt"));
								}
								if (obj.has("e")) {
									detail.setE(obj.getString("e"));
								}
								if (obj.has("rd")) {
									detail.setRd(obj.getString("rd"));
								}
								if (obj.has("p1")) {
									detail.setP1(obj.getString("p1"));
								}
								if (obj.has("p2")) {
									detail.setP2(obj.getString("p2"));
								}
								if (obj.has("p3")) {
									detail.setP3(obj.getString("p3"));
								}
								if (obj.has("p4")) {
									detail.setP4(obj.getString("p4"));
								}

								// 维修信息
								if (obj.has("red")) {
									detail.setRed(obj.getString("red"));
								}
								if (obj.has("rdt")) {
									detail.setRdt(obj.getString("rdt"));
								}
								if (obj.has("rer")) {
									detail.setRer(obj.getString("rer"));
								}
								if (obj.has("rea")) {
									detail.setRea(obj.getString("rea"));
								}
								if (obj.has("w")) {
									detail.setW(obj.getString("w"));
								}
								if (obj.has("edt")) {
									detail.setEdt(obj.getString("edt"));
								}
								if (obj.has("res")) {
									detail.setRes(obj.getString("res"));
								}
								if (obj.has("rcd")) {
									detail.setRcd(obj.getString("rcd"));
								}
							}
							updateUI(detail);
							break;
						case 1:// 数组
							break;
						case -1:// 错误
							dismissDialog(ID_LOADING);
							break;

						default:
							dismissDialog(ID_LOADING);
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
		});
		api.getRepairDetail(1, oddNum, contentType);
	}

	private void updateUI(Detail detail) {
		if (detail != null) {
			current = detail;
			edit_deparment.setText(detail.getD());
			edit_device.setText(detail.getE());
			edit_break.setText(detail.getRd());
			// 维修信息
			edit_confirm_break.setText(detail.getRer());
			edit_suggestion.setText(detail.getRea());
			mSpinner.setSelection(getSelection(R.array.repair_result,detail.getRes()));
			edit_predict_date.setText(detail.getEdt());
			edit_repair_result.setText(detail.getRes());
		}
	}

	private int getSelection(int arrayId, String str) {
		String[] array = getResources().getStringArray(arrayId);
		int result = 0;
		for(int i=array.length-1;i>=0;i--) {
			if(Utils.isNullOrEmpty(str)) {
				result = 0;
			}else {
				if(str.equals(array[i])) {
					result = i;
				}
			}
			
		}
		return result;
	}
	
	private void initTitle() {
		btn_back = (Button) findViewById(R.id.btn_back);
		title_text = (TextView) findViewById(R.id.title_text);
		btn_right = (Button) findViewById(R.id.btn_refresh);
		title_text.setText("维修单查看");
		btn_right.setVisibility(View.VISIBLE);
		btn_right.setText("确定保存");

	}

	private void registerButton() {
		btn_right.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		edit_predict_date.setOnClickListener(this);
	}

	private void initComponents() {

		edit_deparment = (TextView) findViewById(R.id.edit_deparment);
		edit_device = (TextView) findViewById(R.id.edit_device);
		edit_break = (TextView) findViewById(R.id.edit_break);
		edit_confirm_break = (EditText) findViewById(R.id.edit_confirm_break);
		edit_suggestion = (EditText) findViewById(R.id.edit_suggestion);
		mSpinner = (Spinner) findViewById(R.id.edit_repair_man);//维修结果
		predict_item = (LinearLayout)findViewById(R.id.predict_item);
		result_item = (LinearLayout)findViewById(R.id.result_item);
		result_item.setVisibility(View.GONE);
		edit_predict_date = (TextView) findViewById(R.id.edit_predict_date);
		edit_repair_result = (EditText) findViewById(R.id.edit_repair_result);

		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.repair_result, R.layout.spinner_item);
		mSpinner.setAdapter(adapter);
		mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(1==arg2) {
					result_item.setVisibility(View.VISIBLE);
					predict_item.setVisibility(View.GONE);
				}else {
					result_item.setVisibility(View.GONE);
					predict_item.setVisibility(View.VISIBLE);
				}
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		// edit_deparment.setEnabled(false);
		// edit_shangbao_date.setEnabled(false);
		// edit_duty_man.setEnabled(false);
		// edit_device.setEnabled(false);
		// edit_break.setEnabled(false);
		// edit_unit.setEnabled(false);
		// edit_jiebao_date.setEnabled(false);
		// edit_confirm_break.setEnabled(false);
		// edit_suggestion.setEnabled(false);
		// edit_repair_man.setEnabled(false);
		// edit_predict_date.setEnabled(false);
		// edit_repair_result.setEnabled(false);
		// edit_finish.setEnabled(false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.btn_refresh:
			// 修改维修单
			updateRepair();
			break;
		case R.id.edit_predict_date:
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}
	}
	
	private String getSelectionValue(int arrayId, int position) {
		String[] array = getResources().getStringArray(arrayId);
		return array[position];
	}

	private void updateRepair() {
		RepairApi api = new RepairApi(this);
		String rer = edit_confirm_break.getText().toString();
		String rea = edit_suggestion.getText().toString();
		String res = edit_repair_result.getText().toString();
		String edt = edit_predict_date.getText().toString();
		
		if(Utils.isNullOrEmpty(rer)) {
			Utils.showToast(this, "确定故障不能为空");
			return;
		}
		if(Utils.isNullOrEmpty(rea)) {
			Utils.showToast(this, "确定建议不能为空");
			return;
		}
		
		Detail detail = new Detail();
		detail.setI(oddNum);
		detail.setEdt(edt);
		detail.setRer(rer);
		detail.setRea(rea);
		detail.setRes(res);
		
		String handle = getSelectionValue(R.array.repair_result, mSpinner.getSelectedItemPosition());
		if("维修中".equals(handle)) {
			detail.setSt("3");
			if(Utils.isNullOrEmpty(edt)) {
				Utils.showToast(this, "预计日期不能为空");
				return;
			}
		}else {
			detail.setSt("4");
			if(Utils.isNullOrEmpty(res)) {
				Utils.showToast(this, "维修结果不能为空");
				return;
			}
		}
		
		
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				if(!isFinishing()) {
					dismissDialog(ID_LOADING);
				}
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject obj = jsonEntity.getJSONObject("d");
							String result = obj.getString("r");
							if("1".equals(result)) {
								Utils.showToast(ServicesReceiverPaperActivity.this, "保存成功");
								finish();
							}else {
								Utils.showToast(ServicesReceiverPaperActivity.this, "保存失败");
							}
							break;
						case 1:// 数组


							break;
						case -1:// 错误
							Utils.showToast(ServicesReceiverPaperActivity.this, "保存失败");
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				if(!isFinishing()) {
					showDialog(ID_LOADING);
				}
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				
			}
		});
		api.updateRepair(1,oddNum,detail);
	}
}
